import React, { useEffect, useMemo, useState } from 'react';
import { Dropdown, Space, Menu } from 'antd';
import { DownOutlined } from '@ant-design/icons';
import moment from 'moment';
import { useMenuActions, useMenuData, useMenuSelected, useSkipContainer } from '../../store/menuStore';
import Item from 'antd/es/list/Item';
import { useUserInfo } from '../../store/userStore';

const menuFilter = (arr) => {
  return arr.map((item) => {
    let data = { label: item.name, key: item.code }
    if (item.children) {
      data.children = menuFilter(item.children)
    }
    return data
  })
}

const Header = () => {
  const [latesTime, setLatesTime] = useState(moment().format('YYYY-MM-DD HH:mm:ss'));
  const userInfo = useUserInfo()
  const menuData = useMenuData()
  const menuSelected = useMenuSelected()
  const skipContainer = useSkipContainer()
  const {findByCodeMenu} = useMenuActions()
  const modelMenus = useMemo(() => {
    return menuFilter(
      menuData.find((d) => {
        return d.appId === menuSelected?.appId
      })?.children || []
    )
  }, [menuData, menuSelected])

  useEffect(() => {
    // 设置一个定时器
    const timerId = setInterval(() => {
      setLatesTime(moment().format('YYYY-MM-DD HH:mm:ss'));
    }, 1000);
    // 清除定时器
    return () => clearInterval(timerId);
  }, [])

  const onClick = (e) => {
    let activeMenu = findByCodeMenu(e.key)
    if (activeMenu)  {
      skipContainer(activeMenu)
    }
  };
  return (
    <header className="layout-header">
      <div className="pull-left cursor-pointer">
        <div className="logo-p">
          <span>{'应用集成管理'}</span>
        </div>
      </div>
      <div className="layout-top-nav">
      <Menu
          onClick={onClick}
          selectedKeys={[menuSelected?.code]}
          mode="horizontal"
          items={modelMenus}
        />
      </div>
      <div className="pull-right user-setting">
        <span>{latesTime}</span>
        <span className="sep">|</span>
        <Dropdown
          menu={{
            items: [
              {
                key: '1',
                label: '修改密码',
              },
              {
                key: '2',
                danger: true,
                label: '退出系统',
              },
            ],
          }}
          trigger={['click']}
        >
          <a onClick={(e) => e.preventDefault()}>
            <Space>
              {userInfo.userName}
              <DownOutlined />
            </Space>
          </a>
        </Dropdown>
      </div>
    </header>
  );
};
export default Header;
